﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using App.Data;
using App.Core.Extensions;
using System.Text;
using App.Core.Mail;

public partial class Pages_Public_Registration : BasePage
{
    protected IList<BusinessType> _BusinessTypes;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            BindDropdownLists();
        }
    }
    protected void BindPageInfo()
    {
        Page.Title = WebUtil.GetPageTitle("Register With BTC Real Estate");
        lblSignUpSubHeading.Text = String.Format("Please sign-up to be a {0} member.", ConfigReader.ProviderCompany);
    }
    protected void BindDropdownLists()
    {
        //BindDropdownList.Countries(ddlCountry);
        BindDropdownList.Countries(ddlPreferredCountry);
        //BindDropdownList.Cities(ddlPreferredCity, ConfigReader.SiteBusinessCountryID);
        BtcHousingEntities context = new BtcHousingEntities();
        var properties = from P in context.PropertyTypes where P.BusinessTypeID == ConfigReader.DeveloperBusinessTypeID && P.ID != ConfigReader.OtherPropertyTypeID select P;
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("<table cellpadding='0' cellspacing='0' style='width:100%;'>");
        int i = 0;
        foreach (PropertyType property in properties)
        {
            if (i % 2 == 0)
                sb.AppendFormat("<tr>");
            sb.AppendFormat("<td>");
            sb.AppendFormat("<input type='checkbox' id='chkInterestedProperty_{0}' name='chkInterestedProperty' value='{0}'/><label for='chkInterestedProperty_{0}'>{1}</lable>", property.ID.ToString(), property.Name);
            sb.AppendFormat("</td>");
            if (i % 2 > 0)
                sb.AppendFormat("</tr>");
            i++;
        }
        sb.AppendFormat("</table>");
        divPropertyTypes.InnerHtml = sb.ToString();
        
        ///Load Business Types        
        _BusinessTypes = (from P in context.BusinessTypes where P.ParentID == null && P.ID != ConfigReader.IndividualBusinessTypeID select P).ToList();

    }
    [WebMethod]
    public static int RegisterIndividual(App.CustomEntity.Individual individual)
    {
        BtcHousingEntities context = new BtcHousingEntities();
        Contact existingContact = context.Contacts.FirstOrDefault(P => String.Compare(P.Email, individual.Email, true) == 0 && !P.IsDeleted);
        if (existingContact != null)
            return -1;
        Customer customer = new Customer();        
        customer.Name = individual.Name;
        customer.Comment = individual.Feedback;
        customer.Phone = individual.Phone;
        customer.BusinessTypeID = ConfigReader.IndividualBusinessTypeID;
        customer.HasInterestInLoan = individual.InterestedInLoan;        
        customer.Created = DateTime.Now;
        customer.Modified = DateTime.Now;
        customer.IsDeleted = false;
        customer.IsApproved = false;// true;
        customer.IsIndividual = true;
        customer.VerificationKey = System.Guid.NewGuid();
        bool isBangladesh = false;
        isBangladesh = (ConfigReader.CountryIDOfBangladesh == individual.ResidenceCountryID) ? true : false;
        customer.IsBangladeshi = isBangladesh;
        if (!isBangladesh)
        {
            customer.CityName = individual.CityName;            
            customer.PreferredZones = individual.PreferredZones;
            customer.CountryID = individual.ResidenceCountryID;    
        }
        customer.ZipCode = individual.ZipCode;
        customer.Address = individual.Address;
        context.AddToCustomers(customer);
        
        User user = new User();
        user.LoginName = individual.Email;
        user.GroupID = ConfigReader.IndividualUserGroupID;
        user.IsActive = true;
        user.Created = DateTime.Now;
        user.Modified = DateTime.Now;
        user.Password = individual.Password;

        customer.Users.Add(user);

        Contact contact = new Contact();
        contact.Email = individual.Email;
        contact.Name = customer.Name;
        contact.DesignationID = ConfigReader.ManagingBodyDesignationID;
        contact.Created = DateTime.Now;
        contact.Modified = DateTime.Now;
        contact.ModifiedBy = user.ID;
        customer.Contacts.Add(contact);

        if (isBangladesh)
        {
            String[] zones = individual.PreferredZones.Split(',');
            foreach (String zoneID in zones)
            {
                if (!zoneID.IsNullOrEmpty())
                {
                    CustomerPreferredZone pfZone = new CustomerPreferredZone();
                    pfZone.ZoneID = zoneID.ToInt();
                    customer.CustomerPreferredZones.Add(pfZone);
                }
            }
        }       

        String[] propertyTypes = individual.InterestedOn.Split(',');
        foreach (String propertyID in propertyTypes)
        {
            if (!propertyID.IsNullOrEmpty())
            {
                CustomerPropertyType propertyType = new CustomerPropertyType();
                propertyType.PropertyTypeID = propertyID.ToInt();
                customer.CustomerPropertyTypes.Add(propertyType);
            }
        }

        int affectedRows = context.SaveChanges();
        if (affectedRows == 0)
            return -3;

        SendVerificationEmail(customer, customer.Name, contact.Email);
        return 1;
    }

    [WebMethod]
    public static int RegisterCompany(App.CustomEntity.Cusomer clientCustomer)
    {
        BtcHousingEntities context = new BtcHousingEntities();
        ///Unique Validations
        Contact existingContact = context.Contacts.FirstOrDefault(P => String.Compare(P.Email, clientCustomer.ContactEmail, true) == 0 && !P.IsDeleted);
        if (existingContact != null)
            return -1;

        User existingUser = context.Users.FirstOrDefault(P => String.Compare(P.LoginName, clientCustomer.UserName, true) == 0 && !P.IsDeleted);
        if (existingUser != null)
            return -2;

        Customer customer = new Customer();
        customer.Name = clientCustomer.CompanyName;
        customer.IsRehabMember = clientCustomer.IsRehabMember;  // Newly Added by Siddik 15.09.11 
        customer.Address = clientCustomer.Address;
        customer.Comment = clientCustomer.Feedback;
        customer.BusinessDetails = clientCustomer.BusinessDetails;
        
        customer.BusinessTypeID = clientCustomer.BusinessTypeID;
        //customer.HasInterestInLoan = clientCustomer.InterestedInLoan;
        customer.Created = DateTime.Now;
        customer.Modified = DateTime.Now;
        customer.IsDeleted = false;
        customer.IsApproved = false;//true;
        customer.IsIndividual = clientCustomer.BusinessTypeID == ConfigReader.IndividualBusinessTypeID ? true : false;
        customer.VerificationKey = System.Guid.NewGuid();

        context.AddToCustomers(customer);

        User user = new User();
        user.LoginName = clientCustomer.UserName; //clientCustomer.ContactEmail;
        user.GroupID = clientCustomer.BusinessTypeID == ConfigReader.DeveloperBusinessTypeID ? ConfigReader.DeveloperUserGroupID : ConfigReader.ServiceProviderUserGroupID;
        user.IsActive = true;
        user.Created = DateTime.Now;
        user.Modified = DateTime.Now;
        user.Password = clientCustomer.Password;

        customer.Users.Add(user);

        Contact contact = new Contact();
        contact.Email = clientCustomer.ContactEmail;
        contact.Name = clientCustomer.ContactName;
        contact.DesignationID = ConfigReader.ManagingBodyDesignationID;
        contact.Created = DateTime.Now;
        contact.Modified = DateTime.Now;
        contact.ModifiedBy = user.ID;
        customer.Contacts.Add(contact);

        // Assign Free Member Ship

        //if (clientCustomer.BusinessTypeID == ConfigReader.DeveloperBusinessTypeID)
        //{

            var freePackage = context.Packages.FirstOrDefault(P => P.Price == 0 && P.IsActive);
            if (freePackage != null)
            {
                PackageSubscription freeSubscription = new PackageSubscription();
                freeSubscription.CustomerID = customer.ID;
                freeSubscription.PackageID = freePackage.ID;
                freeSubscription.ProductCount = freePackage.ProductLimit;
                freeSubscription.StartDate = DateTime.Now;
                freeSubscription.IsActiveSubscription = true;
                freeSubscription.ExpireDate = DateTime.Now.AddDays(freePackage.Duration);
                context.AddToPackageSubscriptions(freeSubscription);
            }
        //}
        // End Assign Free Membership

        int affectedRows = context.SaveChanges();

        user.ContactID = contact.ID;
        context.SaveChanges();
        
        if (affectedRows == 0)
            return -3;
        SendVerificationEmail(customer, contact.Name, contact.Email);
        return 1;
    }

    private static void SendVerificationEmail(Customer customer, String name, String toEmail)
    {
        StringBuilder template = new StringBuilder(WebUtil.ReadEmailTemplate(AppConstants.EmailTemplate.COMMON));
        if (template.Length > 0)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("Dear {0},<br/>", name);
            sb.AppendFormat("Your account has been created successfully in {0}. Click on the link below to activate your account.<br /><br />", ConfigReader.ProviderCompany);
            sb.AppendFormat("<a href='{0}{1}?{2}={3}&{4}={5}'>{0}{1}?{2}={3}&{4}={5}</a><br /><br />", WebUtil.GetDomainAddress(),
                AppConstants.Pages.ACCOUNT_ACTIVATION, AppConstants.QueryString.ID, customer.ID
                , AppConstants.QueryString.KEY, customer.VerificationKey.ToString());
            sb.AppendFormat("<b>Note:</b> If you cannot click on the link then Copy it and Paste to your browser's address bar to make your account active.");

            template.Replace(AppConstants.ETConstants.DOMAIN, WebUtil.GetDomainAddress());
            template.Replace(AppConstants.ETConstants.MESSAGE, sb.ToString());
            String fromEmail = ConfigReader.SupportEmail;
            String subject = String.Format("Verify your account at {0}", ConfigReader.ProviderCompany);
            try
            {
                bool isSent = MailManager.SendMail(toEmail, String.Empty, String.Empty, fromEmail, subject, template.ToString());
            }
            catch
            {
                BtcHousingEntities context = new BtcHousingEntities();
                EmailMessage message = new EmailMessage();
                message.Subject = subject;
                message.FromEmail = fromEmail;
                message.ToEmail = toEmail;
                message.Message = template.ToString();
                message.IsSent = false;
                message.Created = DateTime.Now;
                message.AttemptedOn = DateTime.Now;
                context.AddToEmailMessages(message);
                context.SaveChanges();
            }
        }
    }
}